package com.cxy.contentcenter.rocketmq;

import com.alibaba.fastjson.JSON;
import com.cxy.contentcenter.dao.messaging.RocketmqTransactionLogMapper;
import com.cxy.contentcenter.domain.dto.content.ShareAuditDTO;
import com.cxy.contentcenter.domain.entity.messaging.RocketmqTransactionLog;
import com.cxy.contentcenter.service.content.ShareService;
import lombok.RequiredArgsConstructor;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;

/**
 * @author: huayushu luming
 * @date: 2020-12-01 10:01
 * @desc:
 **/
@RocketMQTransactionListener(txProducerGroup = "tx-add-bonus-group")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class AddBonusTransactionListener implements RocketMQLocalTransactionListener {
    private final ShareService shareService;
    private final RocketmqTransactionLogMapper rocketmqTransactionLogMapper;

    /**
     * 执行本地事务
     * @param msg
     * @param arg
     * @return
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        MessageHeaders headers=msg.getHeaders();
        String transactionId=(String)headers.get(RocketMQHeaders.TRANSACTION_ID);
        Integer shareId = Integer.valueOf((String) headers.get("share_id"));
        //有个小坑
        String dto = (String) headers.get("dto");
        ShareAuditDTO shareAuditDTO = JSON.parseObject(dto, ShareAuditDTO.class);
        try {
            this.shareService.auditByIdWithRocketMqLog(shareId, shareAuditDTO,transactionId);
            return RocketMQLocalTransactionState.COMMIT;
        }catch (Exception e){
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    /**
     * 检查本地事务
     * @param msg
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        MessageHeaders headers=msg.getHeaders();
        String transactionId=(String)headers.get(RocketMQHeaders.TRANSACTION_ID);
        //查询事务日志是否存在
        RocketmqTransactionLog rocketmqTransactionLog = this.rocketmqTransactionLogMapper.selectOne(
                RocketmqTransactionLog.builder()
                        .transactionId(transactionId)
                        .build()
        );
        if(rocketmqTransactionLog!=null){
            return RocketMQLocalTransactionState.COMMIT;
        }
        return RocketMQLocalTransactionState.ROLLBACK;
    }
}
